from SmartHouseServer_new.to_send_message import light_num, catDoor_num, door_num, window_num
from SmartHouseServer_new.Database.Sql_Func import select_device_phoneNum, insert_customer, select_device_light, \
    select_device_gate, select_device_window, select_device_garage_door
from SmartHouseServer_new.Device_Func import light, catDoor, door, window
from SmartHouseServer_new.GLOBALVAR import massage_queue
from flask import Flask, request, jsonify
import threading, json

app = Flask(__name__)
l = ['work_mode', 'device']

to_send_Gate = '00'
to_send_Window = '00'
to_send_Light = '00'
to_send_Garaedoor = '0'


@app.route('/test', methods=['POST'])
def test():
    global to_send_Gate, to_send_Window, to_send_Light, to_send_Garaedoor
    global payload_to_send_num
    payload_to_send_num = '0000000'
    request_data = request.json  # 获取请求数据，字典结构

    a = json.loads(request_data['name'])

    device = a.get('device', -1)
    work_mode = a.get('work_mode', -1)
    on_off = a.get('on_off', -1)
    print(device)
    print(work_mode)
    print(on_off)

    # 灯
    if (device == 'light' and (work_mode == 0 or work_mode == 1
                               or work_mode == 2 or work_mode == 3) and (
            on_off == False or on_off == True or on_off == 2)):
        device_light = device
        work_mode_light = work_mode
        on_off_light = on_off
        result, result_2 = light(device_light, work_mode_light, on_off_light)
        to_send_Light = light_num(device_light, work_mode_light, on_off_light)
    # 车库门
    elif device == 'catDoor' and (work_mode == 0 or work_mode == 1) and (
            on_off == False or on_off == True or on_off == 2):
        device_catDoor = device
        on_off_catDoor = on_off
        result, result_2 = catDoor(device_catDoor, on_off_catDoor)
        to_send_Garaedoor = catDoor_num(device_catDoor, on_off_catDoor)
    # 大门
    elif (device == 'door' and (work_mode == 0 or work_mode == 1
                                or work_mode == 2 or work_mode == 3 or work_mode == 4) and (
                  on_off == False or on_off == True or on_off == 2)):
        device_door = device
        work_mode_door = work_mode
        on_off_door = on_off
        result, result_2 = door(device_door, work_mode_door, on_off_door)
        to_send_Gate = door_num(device_door, work_mode_door, on_off_door)
    # 窗户
    elif (device == 'window' and (work_mode == 0 or work_mode == 1
                                  or work_mode == 2 or work_mode == 3) and (
                  on_off == False or on_off == True or on_off == 2)):
        device_window = device
        work_mode_window = work_mode
        on_off_window = on_off
        result, result_2 = window(device_window, work_mode_window, on_off_window)
        to_send_Window = window_num(device_window, work_mode_window, on_off_window)
    else:
        pass

    if to_send_Gate != '00' and to_send_Window == '00' and to_send_Light == '00' and to_send_Garaedoor == '0':
        to_send_Gate_num = to_send_Gate
        payload_to_send_num = to_send_Gate_num + to_send_Window + to_send_Light + to_send_Garaedoor
    elif to_send_Gate == '00' and to_send_Window != '00' and to_send_Light == '00' and to_send_Garaedoor == '0':
        to_send_Window_num = to_send_Window
        payload_to_send_num = to_send_Gate + to_send_Window_num + to_send_Light + to_send_Garaedoor
    elif to_send_Gate == '00' and to_send_Window == '00' and to_send_Light != '00' and to_send_Garaedoor == '0':
        to_send_Light_num = to_send_Light
        payload_to_send_num = to_send_Gate + to_send_Window + to_send_Light_num + to_send_Garaedoor
    elif to_send_Gate == '00' and to_send_Window == '00' and to_send_Light == '00' and to_send_Garaedoor != '0':
        to_send_Garaedoor_num = to_send_Garaedoor
        payload_to_send_num = to_send_Gate + to_send_Window + to_send_Light + to_send_Garaedoor_num
    else:
        payload_to_send_num = to_send_Gate + to_send_Window + to_send_Light + to_send_Garaedoor
    massage_queue.put({
        "payload_to_send": payload_to_send_num
    })
    print(payload_to_send_num)

    # 构造响应
    response = {
        'device on or off': result,
        'import database is true or flase': result_2
        # '设备是否开启': result,
        # '是否存入数据库': result_2
    }
    # 返回响应
    return jsonify(response)


@app.route('/login', methods=['POST'])
def login():
    request_data = request.json  # 获取请求数据，字典结构
    a = json.loads(request_data['name'])
    phoneNum = str(a.get('phoneNum', -1))
    passWord = str(a.get('passWord', -1))
    names = select_device_phoneNum()
    for x in names:
        num_name = 0
        num_password = 0
        if phoneNum == x[0]:
            num_name = num_name + 1
        if passWord == x[1]:
            num_password = num_password + 1
    if num_name == 1 and num_password == 1:
        result = f"ok"
    else:
        result = f"ng"
    # 构造响应
    response = {'result': result}
    # 返回响应
    return jsonify(response)


@app.route('/signin', methods=['POST'])
def signin():
    request_data = request.json  # 获取请求数据，字典结构
    a = json.loads(request_data['name'])
    phoneNum = str(a.get('phoneNum', -1))
    passWord = str(a.get('passWord', -1))
    names = select_device_phoneNum()
    for x in names:
        num_name = 0
        if phoneNum == x[0]:
            num_name = num_name + 1
    if num_name == 0:
        insert_customer(phoneNum, passWord)
        result = f"signin True"
    else:
        result = f"signin False"
    # 构造响应
    response = {'result': result}
    # 返回响应
    return jsonify(response)


@app.route('/select', methods=['POST'])
def select():
    request_data = request.json  # 获取请求数据，字典结构
    a = json.loads(request_data['name'])
    device = str(a.get('device', -1))
    if device == 'light':
        myresult = select_device_light()
    elif device == 'door':
        myresult = select_device_gate()
    elif device == 'window':
        myresult = select_device_window()
    elif device == 'catDoor':
        myresult = select_device_garage_door()
    # 构造响应
    response = {'result': myresult}
    # 返回响应
    return jsonify(response)


class FlaskAPP(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        try:
            app.run(host='0.0.0.0', port=5000)
            # app.run(host='192.168.3.252', port=5000)  # 公网IP:  139.159.235.171
        except Exception as e:
            print(e)


def run_flask():
    flask_app = FlaskAPP()  # 添加一个线程
    flask_app.start()  # 启动线程
    flask_app.join()
    print('threading flask app start')


#
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
